package cn.achao.csr.chat.dao;

import cn.achao.csr.api.model.entity.ChatMsg;
import cn.achao.csr.api.model.req.ChatMessagePageReq;
import cn.achao.csr.base.resp.CursorPageBaseResp;
import cn.achao.csr.chat.mapper.ChatMsgMapper;
import cn.achao.csr.tool.utils.CursorUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatMsgDao extends ServiceImpl<ChatMsgMapper, ChatMsg> {

    private final CursorUtils cursorUtils;

    private static final String NORMAL = "1";

    public Integer getUnReadCount(Long roomId, Date readTime) {
        return lambdaQuery()
                .eq(ChatMsg::getRoomId, roomId)
                .gt(Objects.nonNull(readTime), ChatMsg::getCreateTime, readTime)
                .count();
    }

    public CursorPageBaseResp<ChatMsg> getCursorPage(Long roomId, ChatMessagePageReq req, Long lastMsgId) {
        return cursorUtils.getCursorPageByMysql(this,
                req,
                wrapper -> {
                    wrapper.eq(ChatMsg::getRoomId, roomId);
                    wrapper.eq(ChatMsg::getStatus, NORMAL);
                    wrapper.le(Objects.nonNull(lastMsgId), ChatMsg::getId, lastMsgId);
                },
                ChatMsg::getId);
    }
}

